导航菜单
首页 >  Notifications  > Notifications  

Notifications  

Notifications provide brief, timely, and relevant information related to yourapp when it's not in use.

The Android OS controls many aspects of notifications, but you have control overother aspects. Follow these steps when implementing notifications:

Understand the anatomy of a notification.Choose the type of notification for your use case.Set the notification category that aligns with the type of notificationyou've chosen.TakeawaysConsider the purpose of the notification: why are you alerting your users?Determine notification permission pattern, consider how importantnotifications are to your app and where to ask in your user's journey.Pick your notification template.Create notification content:Header text should succinctly summarize the notification.Content text should preview the notification.Image content if applicable to your app's content.Media keyart and metadata for media template.Make it obvious what your user can do with a notification by providingactions based on their content either with text buttons, typing, or mediacontrols.Include your app icon and set the app icon background color.Set channels and categories for your notifications. This allows the systemand your user to customize what notifications they receive and providespriority behavior.If your app may deliver multiple notifications at once, group notifications.Check out the Android UI Kit on Figma for notificationtemplates.Anatomy of a notification

Notifications are designed to make it easy to scan and use a notification's mostimportant elements. These elements are:

Primary content: this constitutes the most prominent element of anotification. Secondary information, such as a timestamp, is smaller andconsolidated above the primary content.People: if the notification involves a person, an avatar stands out fromthe rest of the content.Actions: users can expand notifications by tapping an indicator icon.Actions are displayed with text labels on a separate background color andlocation.Figure 1: Collapsed notificationNotification header and content

When collapsed, a notification shows the app icon, header text, timestamp,expand indicator, and content text. It can also optionally show a large icon.

Figure 2: Notification header area

1 App icon: The app icon is atwo-dimensional representation of your app's identity. It appears in monochromein the status bar. If your app sends a wide variety of notifications, considerreplacing your app icon with a symbol to distinguish between the different kindsof notifications. See Apply the icon color fordetails.

2 Header text: a brief headline for thenotification or source, such as the account name for users. Content is the mostprominent element of a notification.

3 Timestamp: indicates when a notificationwas sent, such as the time of a missed call.

4 Expand indicator: indicates whether thenotification is in a collapsed or expanded state.

5 Content text: supporting information.

6 Large icon (optional): An image may beadded to reinforce the notification in a meaningful way, such as a messagethat includes an avatar of the sender.

Apply the icon color

Starting in Android 12 (API level 31), the system derives the icon color fromthe notification color you set in the app. If the app doesn't set the color, ituses the system theme color. Previously, the color was gray.

Figure 3: Resulting styled app icon color

For most styles, the system applies this color only if the notification isfor a foreground service notification. However, there is no such requirementfor MediaStyle and DecoratedMediaCustomViewStyle notifications that havea media session attached.

The following snippet shows how to apply the icon color.

val notification = Notification.Builder().setColor(Color.GREEN).setColorized(true).setSmallIcon(R.drawable.app_icon).setStyle(Notification.DecoratedCustomViewStyle()).build()Note: Reserve setting the background color of a notification for highpriority notifications such as navigation, ongoing call, or other similarhigh-priority events.Notification actionsFigure 4: Notification action area

1 Text button actions

2 Filled action buttons

3 Suggested replies

4 Reply text field

Starting with Android 7.0 (API level 24), the system shows actions without iconsto accommodate more text. To accommodate Android Wear devices and devicesrunning Android 6.0 (API level 23) and lower, your app must still provide anicon.

Expanded views

You can use an expanded view to display more information to the user withoutnavigating away from the notification.

When expanded, a notification can provide up to three of any of the followingkinds of actions:

Suggested repliesEmphasized actions (pill-shaped buttons)Standard text actions cancelDon'tInclude text actions that duplicate the behavior of tapping on the notification body. check_circleDoGive the user a chance to interact with the notification. The Google Clock app shows a timer running, but it lets the user pause or add a minute directly from the notification.Enable typing in notifications

You enable the user to type directly into a notification by including a Replyaction. This is designed for typing a small amount of text, such as replying to atext message or jotting a brief note.

For longer-form typing, navigate users to your app to provide them more space toview and edit text.

For messaging apps, we recommend keeping the notification present after the userhas sent the reply, and waiting until the conversation is paused beforeautomatically dismissing it.

Figure 5: A user replying directly in the Android Messages without leaving the notification after tapping ReplyChoose the notification type depending on your use case

Google uses the following notification templates in its Android apps. Thesetemplates can be customized to some extent for your app.

Note: Notifications can vary by device manufacturer.

Check out the Android UI Kit on Figma for notification templates.

Standard template

The standard template is suitable for most notifications, allowing succincttext, a large icon (when applicable), and actions.

Figure 6: Standard notification templateBig text template

The big text template is ideal for displaying blocks of longer text. It lets theuser preview more text after they expand the notification.

Figure 7: Big text template, with option large iconBig picture template

The big picture template is designed for notifications containing an image. Whencollapsed, the notification shows a large icon thumbnail of the picture. Whenexpanded, the notification shows a much larger preview.

Figure 8: Big picture templateProgress template

The progress template is designed for user-initiated activities that take timeto complete. When expanded, a notification that uses this template shows aprogress bar and also includes a "cancel" action that lets the user terminatethis activity. (Non-cancelable activities don't warrant notifications.)

Figure 9: Progress templateMedia template

The media template is designed for letting the user control media currentlyplaying from an app.

When collapsed, the notification can display up to three actions. The largeicon can show a related image such as an album cover.When expanded, the notification displays up to five actions with a largerimage, or six actions with no image. The background and other elements of thenotification automatically inherit the colors from the image.Note: To make your player app appear in the quick setting settings area, create aMediaStyle notification with a valid MediaSession token. See Media controlsfor details.Figure 10: Media templateMessaging template

The MessagingStyle template is designed for real-time communication. Whenexpanded, a notification using this template lets the user reply to messagesfrom within the notification.

Figure 11: Messaging templateCall template

Use the CallStyle template to generate large-format notifications thatinclude a large image attachment and indicate an incoming or outgoing call.

Figure 12: Call templateNotification permissions

As relevant and timely as notifications can be, most notifications arenon-exempt, that is, the user must consent to receiving notifications fromyour app.

There is one exception to this: starting in Android 13 (API level 33), mediasessions and apps that manage phone calls are exempt from asking foruser consent. Pre-existing apps may also be eligible if the useralready has notifications on. See more details in Exemptions.

We strongly recommend that your app provide notification options in settings toallow users to update their notifications preferences.

Prompt the user to opt-in to non-exempt notifications

For non-exempt notifications, prompt the user to indicate whether they want toto opt-in to receiving notifications. Users who explicitly choose to receivenotifications are likely to find them more useful and less intrusive.

Figure 13: Requesting a user's consent for a non-exempt notification

Wait to show the notification dialog prompt:

Describe the benefits notifications provide, and the result of not grantingpermissions for notifications.Provide contextual UI, relating the notification to its features or what itaffects. This UI can take any form to integrate best within your app: forexample card within a fee, bottom sheet, or onboarding screen. Any of theseshould be dismissable.Do not show the notification permission dialog, if the user has dismissed theUI.

Starting in Android 13, users can be re-prompted for notification permissions.

Required notifications

Foreground services perform operations that are noticeable to the user but whilethey're not directly interacting with your app. These services show a status barnotification to make users aware that your app is performing a task in theforeground and is consuming system resources.

Figure 14: Example of fitness app foreground service notification

Because these processes use battery and possibly data, your app must make usersaware of them by showing a non-dismissible notification. The user can't dismissthe notification, so you must provide an action for the user to stop theservice.

The following example shows a notification from a fitness app. The user hasstarted an active workout session, which instantiates a foreground servicetracking the workout session. The app shows the notification to indicate it'stracking walking, with an option to see the workout.

When not to use a notification

Don't use notifications for any of the following use cases:

For cross-promotion or advertisement of another product (this is strictlyprohibited by the Play Store)If the user has never opened your appAs the primary method of communication with usersTo encourage the user to return to an app, but provide no direct value (forexample, "Haven't seen you in a while!")For requests to rate your appFor operations that don't require user involvement, such as syncinginformationTo announce error states the app may recover from without user interactionFor holiday or birthday messages cancelDon'tSend holiday or birthday greetings in the form of notifications. cancelDon'tInterrupt the user in the middle of a task for the sole purpose of asking if you're doing a good job.Behavior

Be aware of the following notification behaviors and how to handle them incertain contexts.

Notification arrival

When a notification arrives, Android adds it to the notification drawer.Depending on the parameters you set and the current state of the device, thenotification may perform any of the following actions:

Make a sound or cause phone vibration.Display in the status bar with an icon; this is typically your app icon, butif you have multiple types of notifications, use a symbol that captures thenotification's purpose.Display as a heads-up notification, peeking onto the current screen to grabthe user's attention.

As always, the user can choose to alter the notification behaviors you set.

Figure 15:Notification arrival

1 Notification indicator in the status bar, indicating that there's a notification in the notification drawer.

2 Notification "peeking" onto the current screen to grab a user's attention in the middle of a task.

Notification drawer

The notification drawer in Android typically shows notifications inreverse-chronological order, with adjustments influenced by the followingconditions:

The app's stated notification priority or importanceWhether the notification recently alerted the user with a sound or vibrationAny people attached to the notification and whether they are starred contactsWhether the notification represents an important ongoing activity, such as aphone call in progress or music playingAlterations of the appearance of some notifications by the Android OS at thetop and bottom of the list by adding emphasis or deemphasis, which helps theuser scan content

Handle stale notifications

The notification drawer is designed to show users information that is relevantfor the current moment in time. If an earlier notification is stale, that is,no longer relevant, dismiss it so the user doesn't see it.

Figure 16: Just-arrived text appears at the top of the notification drawer, with a lower priority notification about a photo being added at the bottomNew notifications indicated by app icon badge

In supported launchers on devices running Android 8.0 (API level 26) and higher,app icons display a notification dot to indicate that the app has a newnotification associated with it. These dots appear by default in launcher appsthat support them, and there's nothing your app needs to do. Badging can also bedisabled and limited.

Figure 17: Notification dot on an app icon, indicating the app has a new notification associated with itActions users can perform with notifications

Notifications can enable users to perform any of the following actions:

Navigate to a destination: to navigate, a user may tap a notification. If thenotification displays on a locked screen, the user needs to double-tap it andthen enter their PIN, pattern, or password.

When the user taps a notification, your app must display UI that relatesdirectly to that notification and lets the user take immediate action. Forexample, if the notification says it's their turn in a two-player game,tapping the notification should take them directly to that game.

See an expanded view of the notification: an expand indicator appears in theheader. A user can tap the indicator or swipe down the notification body toexpand it.

Figure 18: Expanded notification

Dismiss the notification (if permitted): a user can dismiss it by swiping itleft or right.

Ongoing notifications that indicate a continuing process in the background, suchas music playing, may not be dismissed with a swipe.

Snooze a heads-up notification: a user can swipe up on a heads-upnotification, and no further notifications from that event are allowed topulse for one minute.

Control similar notifications in the future: users can access notificationcontrols by:

Touching & holding an individual notificationSwiping the notification left or right, and then tapping the settings icon

The controls displayed vary depending on the Android version and whether the apphas channels for its notifications (starting in Android 8.0).

Group multiple notifications

For apps that generate multiple notifications of the same type, Android offersnotification grouping to avoid overwhelming users.

Your app can present multiple notifications according to the followinghierarchy.

A parent notification displays a summary of its child notifications.If the user expands the parent notification, Android reveals all childnotifications.A user can expand a child notification to reveal its entire content.

Android presents child notifications without duplicate header information. Forexample, if a child notification has the same app icon as its parent, thechild's header doesn't include an icon.

Child notifications must be understandable if they appear solo, as the systemmay show them outside of the group when they arrive.

Figure 19: Grouped notifications collapsed and expanded views.

SettingsChannels

Starting in Android 8.0 (API level 26), all notifications must be assigned to achannel. For each channel, you can set the visual and auditory behavior that isapplied to all notifications in that channel. Users can change these settingsand decide which notification channels from your app can be intrusive orvisible.

For details on how to implement this, see Create and manage notificationchannels.

Importance should be chosen with consideration for the user's time andattention. When an unimportant notification is disguised as urgent, it canproduce unnecessary alarm.

Importance Behavior Usage Examples HIGH Makes a sound and appears on screen Time-critical information that the user must know, or act on, immediately Text messages, alarms, phone calls DEFAULT Makes a sound Information that should be seen at the user’s earliest convenience, but not interrupt what they're doing Traffic alerts, task reminders LOW No sound Notification channels that don't meet the requirements of other importance levels New content the user has subscribed to, social network invitations MIN No sound or visual interruption Non-essential information that can wait or isn’t specifically relevant to the user Nearby places of interest, weather, promotional content Pre-defined categories

Whether you're using channels or not, assign each individual notification to themost suitable predefined category. Android may use this information to makeranking and filtering decisions.

Category Description CATEGORY_CALL Incoming call (voice or video) or similar synchronous communication request CATEGORY_MESSAGE Incoming direct message (SMS, instant message, etc.) CATEGORY_EMAIL Asynchronous bulk message (email) CATEGORY_EVENT Calendar event CATEGORY_PROMO Promotion or advertisement CATEGORY_ALARM Alarm or timer CATEGORY_PROGRESS Progress of a long-running background operation CATEGORY_SOCIAL Social network or sharing update CATEGORY_ERROR Error in background operation or authentication status CATEGORY_TRANSPORT Media transport control for playback CATEGORY_SYSTEM System or device status update. Reserved for system use. CATEGORY_SERVICE Indication of running background service CATEGORY_RECOMMENDATION A specific, timely recommendation for a single thing. For example, a news app might recommend a news story the user might want to read next. CATEGORY_STATUS Ongoing information about device or contextual status Lock screen notifications

If a user has opted to show notifications when their screen is locked, thesenotifications can conceal any content that your app marks as sensitive. Androidevaluates each notification's visibility level to determine what can safely beshown.

Set sensitivity level for content on lock screens

User privacy is critically important, so be aware that there are differentlevels of notification that can be visible on the lock screen. For eachnotification you create, you must set the visibility level to public, private,or secret.

Public notifications are fully visible on secure lock screens.Secret notifications are hidden.Private notifications fall in the middle: they show only basic information,including the name of the app that posted it and its icon. Instead of theregular content—which is hidden—you can optionally to show text thatdoesn't reveal personal information, such as 2 new messages.

In the following example, lock screen notifications for the Gmail and Photosapps show all content after the user has chosen to show this information on thelock screen.

Figure 20: Lock screen with different sensitivity levels.

1 All notification content shown on the lock screen

2 Sensitive notification content hidden on the lock screen

StyleClear and concise text

Android truncates content titles to a single line (even when expanded).

A good content title adheres to the following guidelines:

Doesn't exceed 30 charactersContains the most important informationAvoids variables (unless they contain a number or short text string, or arepreceded by text)Excludes the app's name, which already appears in the header cancelDon'tShow the app name in the content title, which is redundant with the header area and uses available characters. check_circleDoShow the most important information in the content title.

Good content text adheres to the following guidelines:

Avoids exceeding the 40-character limitAvoids repeating what's in the content titleThe large icon

Use the large icon for use cases in which imagery meaningfully reinforces thenotification's content. Some examples are:

Communications from another person, such as the image of someone sending amessageThe source of content if it's different than the app sending the notification,such as the logo from a YouTube channel a user is subscribed toMeaningful symbols about the notification, such as an arrow symbol for drivingdirections

Large icons must be circular when showing a person, but square in all othercases.

cancelDon'tUse the large icon for branding. check_circleDoUse the large icon to reinforce a notification's content in a meaningful way, such as a displaying person's photo attached to a message notification.Android version updates

The Android notification system UI and the notification-related APIs continuallyevolve. For a list of these changes check out the notificationcompatibility.

Platform ConsiderationsWear

If the user has a paired Wear OS device, all your notifications appear thereautomatically, including expandable detail and action buttons. For details, seethe design page for notifications on Wear.

相关推荐: